package com.lwq.commentTool.util;

import java.lang.reflect.Type;
import com.google.gson.Gson;

public class GsonUtil
{
	private static final Gson gson = new Gson();

	private GsonUtil()
	{
	}

	/**
	 * 把json字符串解析成指定的Type
	 * 
	 * @param json
	 *            需要解析的json字符串
	 * @param typeOfT
	 *            指定需要解析的类型
	 */
	public static <T> T jsonToModel(String json, Type typeOfT)
	{
		if (json != null)
		{
			return gson.fromJson(json, typeOfT);
		} else
		{
			return null;
		}
	}

	public static <T> T FileToModel(String path, Type typeOfT)
	{
		String json = (String)FileUtil.readFileData(path, 0, FileUtil.FILEEND, FileUtil.DATATYPE_STRING);
		return jsonToModel(json, typeOfT);
	}
	
	/**
	 * 把指定的type型转化为json字符串
	 * 
	 * @param itemContent
	 * @return
	 */
	public static String modelToJson(Object typeOfT)
	{
		if (typeOfT != null)
		{
			return gson.toJson(typeOfT);
		} else
		{
			return null;
		}
	}
	
	public static void modelToFile(Object typeOfT,String path)
	{
		String json = modelToJson(typeOfT);
		FileUtil.writeFileData(path, json);
	}
}